const charset = require('superagent-charset');
const superagent =  charset(require('superagent'));
require('superagent-proxy')(superagent);

const {
    getTaskPage,
    wxpusher,
} = require('./ti_scan_config');

const {
    readTask,
} = require('./ti_logic_read_task');

const {
    logger,
    sleep,
    httpGet,
    httpPost,
} = require('./util');

process.on('unhandledRejection', error => {
    //...不处理...
});

const serialMap = {};//已启动到任务

//每N秒重新拉取任务列表
(async () => {
    const url = 'https://bomcross.ti.com/zh-cn/search?searchTerm=';
    const referer = 'https://bomcross.ti.com/zh-cn/';

    while (1) {
        const tasks = await readTask(getTaskPage);
        if (!tasks) {
            await sleep(5000);
            continue;
        }

        const taskSerials = [];
        let counter = 0;
        //启动任务
        for (const task of tasks) {
            if (task.status != 1) continue;
            taskSerials.push(task.serial);

            if (!serialMap[task.serial]) {
                serialMap[task.serial] = 1;

                (async (serial, counter) => {
                    if (counter % 10 > 0) {
                        await sleep(counter % 10 * 1000);
                    }
                    logger(counter, serial, '启动');

                    while (1) {
                        if (!serialMap[serial]) {
                            logger(serial, '关闭');
                            return;
                        }
                        const fullUrl = url + encodeURIComponent(serial);
                        let html;
                        try {
                            html = await httpGet(fullUrl, referer);
                        } catch(e) {
                            logger(e);
                            await sleep(20000);
                            continue;
                        }
                        const match = html.match(/\<span class=\"j-available-qty\">([\d ,]+)\<\/span\>/);
                        if (!match) {
                            logger(serial, '打开页面出错');
                        } else {
                            if (match[1] && match[1] != '0') {
                                const stock = match[1];

                                const msg = `规格 ${serial} 有 ${stock} 库存可以下单`;
                                logger(msg);

                                try {
                                    //推送消息
                                    await httpPost('http://wxpusher.zjiecode.com/api/send/message', JSON.stringify({
                                        appToken: wxpusher.appToken,
                                        content: msg,
                                        contentType: 1,
                                        uids: wxpusher.uids,
                                    }), 'application/json');
                                } catch(e) {
                                    logger(e);
                                }
                                await sleep(60000);
                            } else {
                                //logger(serial, '无库存');
                            }
                        }

                        await sleep(2000);
                    }
                })(task.serial, counter++);
            }
        }

        //关闭任务
        for (const serial in serialMap) {
            if (taskSerials.indexOf(serial) < 0) {
                delete serialMap[serial];
            }
        }

        await sleep(30000);
    }
})();
